package com.chinacoal.microservice.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.*;
import com.chinacoal.microservice.pojo.*;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.ContractManagementService;
import com.chinacoal.microservice.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 运维管理-合同管理-实现类
 * @date 2020-11-16 10:07
 */
@Slf4j
@Service
public class ContractManagementServiceImpl implements ContractManagementService {

    @Autowired
    private CcmsSmartleasingContractMapper  contractMapper;

    @Autowired
    private CcmsSmartleasingAuditRecodsMapper auditRecodsMapper;

    @Autowired
    private CcmsSmartleasingTenantMapper tenantMapper;

    @Autowired
    private CcmsSmartleasingRoomMapper roomMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @Description: 获取所有的合同信息（带分页）
     * @author zhuliang
     * @date 2020/11/17 9:22
     */
    @Override
    public Result<List<CcmsSmartleasingContract>> getAllContract(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页条件
        Page<CcmsSmartleasingContract> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询所有合同信息
        List<CcmsSmartleasingContract> contracts = contractMapper.getAllByPage(toPage,
                                                                                currency.getProperty(),
                                                                                currency.getManagementOffice());

        //返回分页信息和结果集
        return Result.success(contracts, toPage.getTotal());
    }

    /**
     * @Description: 退租
     * @author zhuliang
     * @date 2020/11/17 11:20
     */
    @Override
    public Result rentCancellation(CcmsSmartleasingContract contract, String token){
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //修改合同信息,和房间状态
        contractMapper.updateByRentCancellation(currency.getLoginId(),
                                                new Date(),
                                                contract.getContractActualEndTime(),
                                                contract.getCauseDescription(),
                                                new Byte("2"),
                                                contract.getActualRefund(),
                                                contract.getRefundInstructions(),
                                                contract.getPkContractId(),
                                 "ca68415c-1df1-11eb-9143-00ffb95445a5",
                                                currency.getProperty(),
                                                currency.getManagementOffice());

        return Result.success();
    }

    /**
     * @Description: 根据合同id查询合同信息
     * @author zhuliang
     * @date 2020/11/17 13:58
     */
    @Override
    public Result<CcmsSmartleasingContract> getContractById(String pkContractId, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //根合同id查询合同信息
        CcmsSmartleasingContract contract = contractMapper.getContractById(pkContractId,
                                                                            currency.getProperty(),
                                                                            currency.getManagementOffice());

        //拆分地址
        if (null != contract) {
            if (StringUtils.isNotEmpty(contract.getFkUpPhotoId())) {
                String[] splitPhotos = contract.getFkUpPhotoId().split(",");
                contract.setFkUpPhotoIdList(splitPhotos);
            }
            if (StringUtils.isNotEmpty(contract.getFkContractOriginalId())){
                String[] splitOriginal = contract.getFkContractOriginalId().split(",");
                contract.setFkContractOriginalIdList(splitOriginal);
            }
        } else {
            log.error(CodeMsg.NOT_FOUND.toString() + "-->合同信息无权访问，或数据丢失-->" + pkContractId);
            return Result.error(CodeMsg.NOT_FOUND);
        }

        //判断其是否审核
        if (contract.getContractAuditState() != 0) {
            //根据审核记录id查询审核记录信息
            List<CcmsSmartleasingAuditRecods> auditRecods = auditRecodsMapper.getByCotractId(contract.getPkContractId());

            //将审核记录信息加入结果中
            contract.setAuditRecods(auditRecods);
        }

        return Result.success(contract);
    }

    /**
     * @Description: 修改合同信息和租户信息
     * @author zhuliang
     * @date 2020/11/17 14:42
     */
    @Transactional
    @Override
    public Result updateContract(CcmsSmartleasingContract contract, String token){
        //验证信息
        if ("0".equals(contract.getTenantType())) {
            if (!IdcardUtils.validateCard(contract.getIdcardNumber())) {
                log.error(CodeMsg.ID_CARD_ABNORMAL.toString() + "-->身份证:" + contract.getIdcardNumber());
                return Result.error(CodeMsg.ID_CARD_ABNORMAL);
            }
        }
        if (!IdcardUtils.isEmail(contract.getEmail())) {
            log.error(CodeMsg.EMAIL_ABNORMAL.toString() + "-->邮箱:" + contract.getEmail());
            return Result.error(CodeMsg.EMAIL_ABNORMAL);
        }
        if (!IdcardUtils.isPhoneLegal(contract.getContactPhone())) {
            log.error(CodeMsg.PHONE_ABNORMAL.toString() + "-->电话号码:" + contract.getContactPhone());
            return Result.error(CodeMsg.PHONE_ABNORMAL);
        }

        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //判断是否有此租户
        String tenantId = tenantMapper.inquireIsThereTenant(contract.getIdcardNumber(), contract.getTenantType());

        //完善租户信息
        CcmsSmartleasingTenant tenant = new CcmsSmartleasingTenant();
        tenant.setLastUpdateDate(new Date());
        tenant.setLastUpdatedBy(currency.getLoginId());
        tenant.setTenantType(contract.getTenantType());
        tenant.setTenantName(contract.getTenantName());
        tenant.setIdcardNumber(contract.getIdcardNumber());
        tenant.setContactPhone(contract.getContactPhone());
        tenant.setEmail(contract.getEmail());
        tenant.setTenantPassword(contract.getContactPhone().substring(contract.getContactPhone().length() - 6));
        if ("1".equals(tenant.getTenantType())) {
            tenant.setAddress(contract.getAddress());
            tenant.setContacts(contract.getContacts());
            tenant.setFkUpPhotoId(contract.getFkUpPhotoId());
            tenant.setEnterpriseLegalPerson(contract.getEnterpriseLegalPerson());
        }

        //如果有此租户，就修改其信息
        if (StringUtils.isNotBlank(tenantId)) {
            //租户电话号码唯一性验证
            String s = tenantMapper.identityUniquenessVerification(contract.getContactPhone(), contract.getTenantType(), tenantId);
            if (StringUtils.isNotBlank(s)) {
                log.error(CodeMsg.NAME_OR_CODE_REPEAT.toString() + "(修改)-->电话号码:" + contract.getContactPhone() + "-->租户：" + tenantId);
                return Result.error(CodeMsg.NAME_OR_CODE_REPEAT);
            }

            //修改租户信息
            tenant.setPkTenantId(tenantId);
            tenantMapper.updateById(tenant);
        } else {
            //租户电话号码唯一性验证
            String s = tenantMapper.identityUniquenessVerification(contract.getContactPhone(), contract.getTenantType(), null);
            if (StringUtils.isNotBlank(s)) {
                log.error(CodeMsg.NAME_OR_CODE_REPEAT.toString() + "(修改)-->电话号码:" + contract.getContactPhone());
                return Result.error(CodeMsg.NAME_OR_CODE_REPEAT);
            }

            tenantId = UUID.randomUUID() + "";

            //完善信息
            tenant.setCreationDate(new Date());
            tenant.setCreatedBy(currency.getLoginId());
            tenant.setPkTenantId(tenantId);
            tenant.setTenantStatus(new Byte("0"));
            tenant.setPayment("0");

            //添加租户信息
            tenantMapper.insert(tenant);
        }

        //修改合同信息
        contract.setLastUpdatedBy(currency.getLoginId());
        contract.setLastUpdateDate(new Date());
        contract.setFkTenantId(tenantId);

        //根据id修改租户和合同的信息
        contractMapper.updateById(contract);

        //判断是否修改了房间
        if (!contract.getFkRoomId().equals(contract.getOldRoomId())) {
            //修改房间状态
            String newString = contractMapper.determineRoomStatus(contract.getFkRoomId());
            if (StringUtils.isBlank(newString)) {
                roomMapper.updateStatusBySurrender(new Date(), currency.getLoginId(), "e0477252-1ed1-11eb-9143-00ffb95445a5", contract.getFkRoomId());
            }

            String oldString = contractMapper.determineRoomStatus(contract.getOldRoomId());
            if (StringUtils.isBlank(oldString)) {
                roomMapper.updateStatusBySurrender(new Date(), currency.getLoginId(), "ca68415c-1df1-11eb-9143-00ffb95445a5", contract.getOldRoomId());
            }
        }

        return Result.success();
    }

    /**
     * @Description: 审核
     * @author zhuliang
     * @date 2020/11/17 15:57
     */
    @Transactional
    @Override
    public Result reviewContract(CcmsSmartleasingAuditRecods auditRecods, String token){
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //验证是否有审核了的合同的时间重叠
        String timeVerification = contractMapper.timeVerification(auditRecods.getContractStartTime(), auditRecods.getFkRoomId());
        if (StringUtils.isNotBlank(timeVerification)) {
            log.error(CodeMsg.CONTRACT_START_TIME_OVERLAPPING.toString() + "-->房间:" + auditRecods.getFkRoomId() + "-->开始时间：" + auditRecods.getContractStartTime());
            return Result.error(CodeMsg.CONTRACT_START_TIME_OVERLAPPING);
        }

        //完善审核记录信息
        auditRecods.setPkAuditRecodsId(UUID.randomUUID() + "");
        auditRecods.setAuditTime(new Date());
        auditRecods.setReviewer(currency.getLoginId());
        auditRecods.setReviewerName(currency.getLoginName());

        //添加审核记录
        auditRecodsMapper.insert(auditRecods);

        //根据合同id查询合同信息
        CcmsSmartleasingContract contract = contractMapper.selectById(auditRecods.getFkContractId());

        //修改合同信息参数
        contract.setLastUpdateDate(new Date());
        contract.setLastUpdatedBy(currency.getLoginId());
        contract.setContractAuditState(auditRecods.getAuditOpinion());

        //如果审核通过，则修改租户信息状态,和房间状态
        if (auditRecods.getAuditOpinion() == 2) {
            CcmsSmartleasingTenant tenant = tenantMapper.selectById(contract.getFkTenantId());
            tenant.setTenantStatus(new Byte("1"));
            tenant.setLastUpdatedBy(currency.getLoginId());
            tenant.setLastUpdateDate(new Date());
            tenantMapper.updateById(tenant);

            //判断是否到了生效时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            if (sdf.format(contract.getContractStartTime()).equals(sdf.format(new Date())) || new Date().after(contract.getContractStartTime())) {
                roomMapper.updateStatusBySurrender(new Date(), currency.getLoginId(), "bbf1d3f0-1df1-11eb-9143-00ffb95445a5", contract.getFkRoomId());

                //修改为已生效
                contract.setContractState(new Byte("1"));
            } else {
                //修改为待生效
                contract.setContractState(new Byte("0"));
            }
        }

        //修改合同信息
        contractMapper.updateById(contract);

        return Result.success();
    }

    /**
     * @Description: 根据合同id批量删除合同信息
     * @author zhuliang
     * @date 2020/11/17 17:03
     */
    @Override
    public Result deleteContract(String deleteId, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //拆分合同id
        String[] ids =  deleteId.split(",");

        String countByContractState = contractMapper.getCountByContractState(ids);
        if (StringUtils.isNotBlank(countByContractState)) {
            log.error(CodeMsg.CONTRACT_TAKE_EFFECT.toString() + "-->合同:" + ids);
            return Result.error(CodeMsg.CONTRACT_TAKE_EFFECT);
        }

        //根据id批量删除
        contractMapper.updateToDeleteById(currency.getLoginId(),
                                            new Date(),
                                            new Byte("1"),
                                            ids,
                                            currency.getProperty(),
                                            currency.getManagementOffice());

        //查询要修改房间状态的房间id
        String[] inquireRoomId = contractMapper.inquireRoomId(ids);
        if (inquireRoomId.length != 0) {

            //修改房间状态
            roomMapper.batchUpdateStatusBySurrender(new Date(), currency.getLoginId(), "ca68415c-1df1-11eb-9143-00ffb95445a5", inquireRoomId);
        }

        return Result.success();
    }

    /**
     * @Description: 条件查询合同信息（带分页）
     * @author zhuliang
     * @date 2020/11/18 10:38
     */
    @Override
    public Result<List<CcmsSmartleasingContract>> getContractByCondition(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页条件
        Page<CcmsSmartleasingContract> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询
        List<CcmsSmartleasingContract> contractList = contractMapper.getContractByCondition(queryCriteria.getTenantType(),
                                                                                            queryCriteria.getInputString(),
                                                                                            queryCriteria.getContactPhone(),
                                                                                            queryCriteria.getIdcardNumber(),
                                                                                            queryCriteria.getFirstDate(),
                                                                                            queryCriteria.getEndDate(),
                                                                                            queryCriteria.getContractState(),
                                                                                            queryCriteria.getContractNumber(),
                                                                                            toPage,
                                                                                            currency.getProperty(),
                                                                                            currency.getManagementOffice());

        //返回查询结果和分页参数
        return Result.success(contractList, toPage.getTotal());
    }

    /**
     * @Description: 添加合同信息
     * @author zhuliang
     * @date 2020/11/18 14:12
     */
    @Transactional
    @Override
    public Result addContract(CcmsSmartleasingContract contract, String token) {
        //验证信息
        if ("0".equals(contract.getTenantType())) {
            if (!IdcardUtils.validateCard(contract.getIdcardNumber())) {
                log.error(CodeMsg.ID_CARD_ABNORMAL.toString() + "-->身份证:" + contract.getIdcardNumber());
                return Result.error(CodeMsg.ID_CARD_ABNORMAL);
            }
        }
        if (!IdcardUtils.isEmail(contract.getEmail())) {
            log.error(CodeMsg.EMAIL_ABNORMAL.toString() + "-->邮箱:" + contract.getEmail());
            return Result.error(CodeMsg.EMAIL_ABNORMAL);
        }
        if (!IdcardUtils.isPhoneLegal(contract.getContactPhone())) {
            log.error(CodeMsg.PHONE_ABNORMAL.toString() + "-->电话号码:" + contract.getContactPhone());
            return Result.error(CodeMsg.PHONE_ABNORMAL);
        }

        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //判断是否有此租户
        String tenantId = tenantMapper.inquireIsThereTenant(contract.getIdcardNumber(), contract.getTenantType());

        //完善租户信息
        CcmsSmartleasingTenant tenant = new CcmsSmartleasingTenant();
        tenant.setLastUpdateDate(new Date());
        tenant.setLastUpdatedBy(currency.getLoginId());
        tenant.setTenantType(contract.getTenantType());
        tenant.setTenantName(contract.getTenantName());
        tenant.setIdcardNumber(contract.getIdcardNumber());
        tenant.setContactPhone(contract.getContactPhone());
        tenant.setEmail(contract.getEmail());
        tenant.setTenantPassword(contract.getContactPhone().substring(contract.getContactPhone().length() - 6));
        if ("1".equals(tenant.getTenantType())) {
            tenant.setAddress(contract.getAddress());
            tenant.setContacts(contract.getContacts());
            tenant.setFkUpPhotoId(contract.getFkUpPhotoId());
            tenant.setEnterpriseLegalPerson(contract.getEnterpriseLegalPerson());
        }

        //如果有此租户，就修改其信息
        if (StringUtils.isNotBlank(tenantId)) {
            //租户电话号码唯一性验证
            String s = tenantMapper.identityUniquenessVerification(contract.getContactPhone(), contract.getTenantType(), tenantId);
            if (StringUtils.isNotBlank(s)) {
                log.error(CodeMsg.NAME_OR_CODE_REPEAT.toString() + "（新增）-->手机号:" + contract.getContactPhone() + "-->租户：" + tenantId);
                return Result.error(CodeMsg.NAME_OR_CODE_REPEAT);
            }

            //修改租户信息
            tenant.setPkTenantId(tenantId);
            tenantMapper.updateById(tenant);
        } else {
            //租户电话号码唯一性验证
            String s = tenantMapper.identityUniquenessVerification(contract.getContactPhone(), contract.getTenantType(), null);
            if (StringUtils.isNotBlank(s)) {
                log.error(CodeMsg.NAME_OR_CODE_REPEAT.toString() + "（新增）-->手机号:" + contract.getContactPhone());
                return Result.error(CodeMsg.NAME_OR_CODE_REPEAT);
            }

            tenantId = UUID.randomUUID() + "";

            //完善信息
            tenant.setCreationDate(new Date());
            tenant.setCreatedBy(currency.getLoginId());
            tenant.setPkTenantId(tenantId);
            tenant.setTenantStatus(new Byte("0"));
            tenant.setPayment("0");

            //添加租户信息
            tenantMapper.insert(tenant);
        }

        //完善合同信息
        contract.setLastUpdateDate(new Date());
        contract.setCreationDate(new Date());
        contract.setCreatedBy(currency.getLoginId());
        contract.setLastUpdatedBy(currency.getLoginId());
        contract.setContractState(new Byte("3"));
        contract.setContractAuditState(new Byte("0"));
        contract.setPkContractId(UUID.randomUUID() + "");
        contract.setFkTenantId(tenantId);

        //添加合同信息
        contractMapper.insert(contract);

        //判断合同是否是续签
        String s = contractMapper.determineRoomStatus(contract.getFkRoomId());
        if (StringUtils.isBlank(s)) {

            //修改房间状态
            roomMapper.updateStatusBySurrender(new Date(), currency.getLoginId(), "e0477252-1ed1-11eb-9143-00ffb95445a5",contract.getFkRoomId());
        }

        return Result.success();
    }
}
